import { Component, OnInit } from '@angular/core';
import {News} from '../../../model/News';
import {ActivatedRoute, Router} from '@angular/router';
import {NewsService} from '../../../services/news.service';
import {ToastService} from '../../../services/toast.service';
import {NewsCate} from '../../../model/NewsCate';
import {ConfigService} from '../../../services/config.service';

@Component({
  selector: 'app-newsedit',
  templateUrl: './newsedit.component.html',
  styleUrls: ['./newsedit.component.css']
})
export class NewseditComponent implements OnInit {
n:News;
optype:string;
id:string;
cl:Array<NewsCate>;
selectedcate:NewsCate;
  constructor(private parm:ActivatedRoute
  ,private newsservice:NewsService
  ,private router:Router
  ,private toastservice:ToastService
  ,public config:ConfigService
  ) {
    this.n=new News();
    this.cl=newsservice.getNewsCategory();
    this.selectedcate=new NewsCate();

    this.optype=parm.snapshot.paramMap.get("optype");
    if(this.optype=='update'){
      this.id=this.parm.snapshot.paramMap.get("id");
      this.getNews();
    }
  }

  ngOnInit(): void {
  }

  save(){
    console.dir(this.n);
    this.n.cate=this.selectedcate.newscateid;
    this.newsservice.saveNews(this.n)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.cancel();
        }
        else {
          //提示错误
          this.toastservice.showError('保存信息异常，请刷新后重试');
        }
      })
  }

  cancel(){
    this.router.navigate(["/admin/newslistforadmin"]);
  }

  getNews(){
    this.newsservice.getNews(this.id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.n=new News();
          this.n=data.obj;
          if(this.n.cate!==null&&this.n.cate!==''){
             this.setCateByid(this.n.cate);
          }
        }
        else {
          //提示错误信息
          this.toastservice.showError('获取信息异常，请重试');
          this.cancel();
        }
      })


  }
onCateSelectd(c:NewsCate){
    this.selectedcate=c;
}

 onFileChange(event:any){
    let touploadfile=event.target.files[0];
    console.dir(touploadfile);
    this.newsservice.uploadPic(touploadfile)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.n.coverpic=data.filename;
        }
        else {
          this.toastservice.showError('上传图片出错，请刷新后重试');
        }
      })

 }
setCateByid(id:string){
    for(let i=0;i<this.cl.length;i++){
      if(this.cl[i].newscateid==id){
        this.selectedcate=this.cl[i];
      }
    }
}

}
